
package com.kweative.cluster.data;

import com.kweative.cluster.Cluster;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class CObject<T> implements Serializable {
	private static int nextId = 0;
	private String id;
	private T value = null;
	private CObject parent = null;
	private boolean changed = false;
	private int original;

	public CObject(String id,T value) {
		this.id = id;
		this.value = (T) Cluster.get(id, (Serializable) value);
		original = this.value.hashCode();
	}
	public CObject<T> set(T value) {
		if (this.value.equals(value)) return this;
		this.value = value;
		changed = true;
		return this;
	}
	public T get() {
		return value;
	}
	public boolean hasChanged() {
		return changed || value.hashCode() != original;
	}
	public void commit() {
		if (!hasChanged()) return;
		Cluster.store(id, (Serializable) value);
		original = this.value.hashCode();
	}

	@Override
	public String toString() {
		return value.toString();
	}

	@Override
	protected void finalize() throws Throwable {
		if (hasChanged())
			Logger.getAnonymousLogger().log(Level.SEVERE,"Object was not comitted before garbage collected:" + id);
	}

}
